package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheRedis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.*;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    private StringRedisTemplate redis;
    private final static ExecutorService executor = new ThreadPoolExecutor(10, 10, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(10));
    @Autowired
    private  CacheRedis cacheRedis;//??

    @Override
    public Result queryById(Long id) {
        //缓存穿透
        //Shop shop = cacheRedis.queryWithPassThrough(CACHE_SHOP_KEY,Shop.class,id, this::getById,CACHE_SHOP_TTL,TimeUnit.MINUTES);
        //缓存击穿-互斥锁
        Shop shop = cacheRedis.queryWithMutex(CACHE_SHOP_KEY, LOCK_SHOP_KEY, Shop.class, id, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //缓存击穿-逻辑过期时间
        //Shop shop = cacheRedis.queryWithLogicExpire(CACHE_SHOP_KEY, LOCK_SHOP_KEY, Shop.class, id, this::getById, 1L, TimeUnit.MINUTES);

        if(shop == null){
            return Result.fail("不存在该店铺");
        }

        return Result.ok(shop);
    }
    @Override
    @Transactional
    public Result updateShopById(Shop shop) {
        //增加事务
        if(shop.getId() == null){
            return Result.fail("id不存在");
        }
       //修改数据库
        updateById(shop);
        // 删除缓存
        redis.delete(CACHE_SHOP_KEY + shop.getId());
        //返回结果
        return Result.ok();
    }




}
